import React, {Component} from 'react';

import { checkAndGetDatas, comfirmText } from 'utils/tools';
import  RecomCourseService from 'services/RecomCourse';
import CommonService from 'services/CommonService'
import { RECOM_COURSE_TH } from 'config/table_config'; 

import ListTitleCon from 'components/commonCon/ListTitleCon';
import TableHeadCon from 'components/commonCon/TableHeadCon';
import TableBodyCon from './TableBodyCon';

import './index.scss';

const recomCourseService = new RecomCourseService(),
      commonService = new CommonService(),
      cfmText = comfirmText ('RECOM_COURSE');

class RecomCourseCon extends Component {

  constructor (props) {
    super (props);
    this.state = {
      title: '推荐课程管理',
      recomCourseData: []
    }
  }

  componentDidMount () {
    this.getRecomCourse();
  }

  /* 获取课程数据*/
  async getRecomCourse () {
    const res = await recomCourseService.getRecomCourseData();
    const data = await checkAndGetDatas(this, res); //传入this如res进行判断操作

    this.setState({
      recomCourseData: data
    })

    console.log(this.state)
  }

  /* 刷新*/
  async refreshRecomCourse() {
    this.getRecomCourse();
  }

  /* 下架课程*/
  async onStatusClick (cid, index) {
    const { recomCourseData } = this.state,
    status = recomCourseData[index].status,
    text = cfmText(status);

    const cfm = window.confirm(text);

    if(!cfm) {
      return; //取消就返回
    }

    switch(status) {
    case 0:
      recomCourseData[index].status = 1;
      break;
    case 1:
      recomCourseData[index].status = 0;
      break;
    default:
      break;
    }

    this.setState({
      recomCourseData
    }, async ()=> {
    const result = await commonService.changeDataStatus({
      id: cid, 
      field: 'RECOM_COURSE',
      status: this.state.recomCourseData[index].status
    })
    console.log(result)
    const errorCode = +result.error_code;
    if(errorCode !== 0) {
      alert(
        status === 0 ? '上架课程失败!' : '下架该失败！'
      )
    }
    })
  }

  render() {
    const { title, recomCourseData } = this.state; //良好习惯，一定要解构
    // const { onRefreshData } = this;
    return (
      <div className="list-container">
        {/* 公共组件 */}
        <ListTitleCon 
          title={title} 
          onRefreshData={this.refreshRecomCourse.bind(this)} />
        <table className="list-table">
          <TableHeadCon thData={ RECOM_COURSE_TH } />
          <TableBodyCon
            recomCourseData={ recomCourseData }
            onStatusClick = { this.onStatusClick.bind(this)} 
          />
        </table>
      </div>
    )
  }
}

export default RecomCourseCon;